<template>
  <div id="login">
    <div class="login_wrap">
      <ul class="menu_tab">
        <li
          v-for="item in menuTab"
          :key="item.id"
          :class="{current: item.current}"
          @click="toggleMenu(item)"
        >{{ item.name }}
        </li>
      </ul>

      <el-form
        :model="loginForm"
        status-icon
        :rules="rules"
        ref="loginForm"
        class="login_form"
      >
        <el-form-item prop="username" class="item_form">
          <label>邮箱</label>
          <el-input
            type="text"
            v-model="loginForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password" class="item_form">
          <label>密码</label>
          <el-input
            type="password"
            v-model="loginForm.password"
            autocomplete="off"
            maxlength="20"
            minlength="6"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item prop="passwords" class="item_form" v-show="model === 'register'">
          <label>重复密码</label>
          <el-input
            type="password"
            v-model="loginForm.passwords"
            autocomplete="off"
            maxlength="20"
            minlength="6"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item prop="code" class="item_form">
          <label>验证码</label>
          <el-row :gutter="10">
            <el-col :span="15">
              <el-input
                v-model="loginForm.code"
                maxlength="6"
                minlength="6"
              ></el-input>
            </el-col>
            <el-col :span="9">
              <el-button
                type="success"
                class="block"
                style="height: 40px"
                @click="getCode"
                :disabled="codeBtnStatus.status"
              >{{ codeBtnStatus.text }}
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            @click="submitForm('loginForm')"
            class="margin_top_19 block"
            :disabled="loginBtnStatus"
          >{{ model == "login" ? "登录" : "注册" }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import sha1 from "js-sha1";
import { getSms, Register, Login } from "@/api/login";
import { reactive, ref, onMounted, onUnmounted } from "@vue/composition-api";
import { stripscript, validateEmail, validatePass, validateVCode } from "@/utils/validate";

export default {
  name: "index",
  // 这里放置data 数据、生命周期、自定义函数
  setup(props, { refs, root }) {
    /*context: {
        attrs: (...) === this.$attrs
        emit: (...) === this.$emit
        listeners: (...) === this.$listeners
        parent: (...) === this.parent
        refs: (...) === this.refs
        root: (...) === this
    }*/
    // 验证邮箱
    let validateUserName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else if (validateEmail(value)) {
        callback(new Error("用户名格式有误"));
      } else {
        callback();
      }
    };
    // 验证密码
    let validatePassword = (rule, value, callback) => {
      loginForm.password = stripscript(value);
      value = loginForm.password;
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (validatePass(value)) {
        callback(new Error("密码为6至20位数字＋字母"));
      } else {
        callback();
      }
    };
    // 验证重复密码
    let validatePasswords = (rule, value, callback) => {
      if (model.value === "login") {
        callback();
      }
      loginForm.passwords = stripscript(value);
      value = loginForm.passwords;
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (value !== loginForm.password) {
        callback(new Error("重复不一致"));
      } else {
        callback();
      }
    };
    // 验证验证码
    let validateCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入验证码"));
      } else if (validateVCode(value)) {
        callback(new Error("验证码格式有误"));
      } else {
        callback();
      }
    };
    const menuTab = reactive([
      { name: "登录", current: true, type: "login" },
      { name: "注册", current: false, type: "register" }
    ]);
    // 模块值
    const model = ref("login");
    // 登录禁用按钮
    const loginBtnStatus = ref(true);
    // 验证码状态
    const codeBtnStatus = reactive({
      status: false,
      text: "获取验证码"
    });
    // 定时器
    const timer = ref(null);
    // 表单
    const loginForm = reactive({
      username: "2717599707@qq.com",
      password: "2000828chi",
      passwords: "2000828chi",
      code: ""
    });
    // 表单验证
    const rules = reactive({
      username: [
        { validator: validateUserName, trigger: "blur" }
      ],
      password: [
        { validator: validatePassword, trigger: "blur" }
      ],
      passwords: [
        { validator: validatePasswords, trigger: "blur" }
      ],
      code: [
        { validator: validateCode, trigger: "blur" }
      ]
    });

    /**
     * 声明方法
     */
      // 切换类型
    const toggleMenu = ((data) => {
        menuTab.forEach((el) => {
          el.current = false;
        });
        // 高光
        data.current = true;
        // 修改模块值
        model.value = data.type;
        // 重置表单
        resetFormData();
      });
    // 重置表单数据
    const resetFormData = (() => {
      refs["loginForm"].resetFields();
    });
    // 更新按钮状态
    const updateBtnStatus = ((params) => {
      codeBtnStatus.status = params.status;
      codeBtnStatus.text = params.text;
    });
    // 获取验证码
    const getCode = (() => {
      if (!loginForm.username) {
        root.$message.error("请输入邮箱");
        return false;
      }
      if (validateEmail(loginForm.username)) {
        root.$message.error("邮箱格式有误");
        return false;
      }
      // 修改按钮状态
      updateBtnStatus({
        status: true,
        text: "发送中"
      });
      // 获取参数
      let requestData = {
        username: loginForm.username,
        module: model.value
      };
      setTimeout(() => {
        getSms(requestData).then(res => {
          // console.log(res);
          let data = res.data;
          root.$message.success(data.message);
          // 启用登录或者注册按钮
          loginBtnStatus.value = false;
          // 开启倒计时
          countDown(60);
        }).catch(error => {
          // 启用登录或者注册按钮
          loginBtnStatus.value = false;
          updateBtnStatus({
            status: false,
            text: "重新发送"
          });
          console.log(error);
        });
      }, 2000);
    });
    // 提交
    const submitForm = ((formName) => {
      refs[formName].validate((valid) => {
        if (valid) {
          model.value === "login" ? login() : register();
        } else {
          console.log("err submit！！");
          return false;
        }
      });
    });
    // 登录
    const login = (() => {
      let requestData = {
        username: loginForm.username,
        password: sha1(loginForm.password),
        code: loginForm.code
      };
      // 请求接口
      // vuex
      root.$store.dispatch("app/login", requestData).then(res => {
        let data = res.data;
        root.$message.success(data.message);
        root.$router.push({
          name: "Layout"
        });
      }).catch(error => {
        console.log(error);
      });
      /* Login(requestData).then((res) => {
          // console.log(res);
           let data = res.data;
           root.$message.success(data.message);
           root.$router.push({
               name: "Layout"
           })
       }).catch((error) => {
           console.log(error);
       });*/
    });
    // 注册
    const register = (() => {
      let requestData = {
        username: loginForm.username,
        password: sha1(loginForm.password),
        code: loginForm.code,
        module: model.value
      };
      // 请求接口
      Register(requestData).then((res) => {
        console.log(res);
        let data = res.data;
        root.$message.success(data.message);
        toggleMenu(menuTab[0]);
        clearCountDown();
      }).catch((error) => {
        console.log(error);
      });
    });
    // 倒计时
    const countDown = ((num) => {
      // 60 and 0 不见了， 故意留bug
      // setTimeout(() => {}, xxx), 清除 clearTimeout(变量); 只执行一次
      // setInterval(() => {}, xxx), 清除 clearInterval(变量); // 不断执行，需要条件才可停止
      // 判断定时器是否存在，存在则清除
      if (timer.value) {
        clearInterval(timer.value);
      }
      let time = num;
      timer.value = setInterval(() => {
        if (time > 0 && time <= time) {
          time--;
          codeBtnStatus.text = `${time}s`;
        } else {
          clearInterval(timer.value);
          updateBtnStatus({
            status: false,
            text: "重新发送"
          });
        }
      }, 1000);
    });
    // 清除倒计时
    const clearCountDown = (() => {
      // 还原验证码按钮默认操作
      updateBtnStatus({
        status: false,
        text: "获取验证码"
      });
      clearInterval(timer.value);
    });

    onMounted(() => {
    });
    // 销毁页面
    onUnmounted(() => {
      // 清除定时器
      clearInterval(timer.value);
    });

    return {
      menuTab,
      model,
      loginBtnStatus,
      codeBtnStatus,
      loginForm,
      rules,
      toggleMenu,
      getCode,
      submitForm
    };
  }
};
</script>

<style scoped lang="scss">
#login {
  display: -webkit-flex;
  display: flex;
  align-items: center;
  -webkit-align-items: center;
  justify-content: center;
  -webkit-justify-content: center;
  width: 100%;
  height: 100vh;
  background-color: #344a5f;
  /*background-image: url("~@/assets/login_bg.svg");
  background-repeat: no-repeat;
  background-position: center 40px;
  background-size: 100%;*/
}

.login_wrap {
  width: 330px;
  margin: auto;
  padding-bottom: 150px;
}

.menu_tab {
  text-align: center;

  li {
    display: inline-block;
    width: 88px;
    line-height: 36px;
    font-size: 14px;
    color: #fff;
    border-radius: 2px;
    cursor: pointer;
  }

  .current {
    background-color: rgba(0, 0, 0, .1);
  }
}

.login_form {
  margin-top: 29px;

  label {
    display: block;
    margin-bottom: 3px;
    font-size: 14px;
    color: #fff;
  }

  .item_form {
    margin-bottom: 13px
  }

  .block {
    display: block;
    width: 100%;
  }
}
</style>
